package com.ecnu.codelearn.thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @Author: 曹培胜
 * @Date: 2021/09/14/14:51
 * @Description:
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;
    private Long end;

    //临界值
    private Long temp = 100_0000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start > temp) { //forkjoin
            // 分支合并计算
            long middle = (start + end) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
            task1.fork();//差分任务，把任务压入线程队列
            task2.fork();//差分任务，把任务压入线程队列
            return task1.join() + task2.join();
        } else {
            long sum = 0;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
        test2();
    }

    public static void test1() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinDemo task = new ForkJoinDemo(0L, 10_0000_0000L);
        // forkJoinPool.execute(task);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);

        Long sum = submit.get();
        long endTime = System.currentTimeMillis();

        System.out.println("sum:" + sum + "时间：" + (endTime-startTime));
    }

    //更快
    public static void test2() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();

        // 并行流计算 （）（]
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        long endTime = System.currentTimeMillis();

        System.out.println("sum:" + sum + "时间：" + (endTime-startTime));


    }

}
